package com.nightpiter.view.drawer.rapid;

import com.nightpiter.view.graphics.Canvas;
import com.nightpiter.view.graphics.PointF;

public class SmoothLinkDrawer extends LinkDrawer {

	private SimpleLinkDrawer simple = new SimpleLinkDrawer();

	private boolean colorCheck(Link first, Link second) {
		if (first.colors.size() != second.colors.size())
			return false;

		int checkedCount = 0;

		for (Integer fc : first.colors) {
			for (Integer sc : second.colors) {
				if (fc.intValue() == sc.intValue()) {
					checkedCount++;
				}
			}
		}

		if (checkedCount == first.colors.size())
			return true;

		return false;
	}

	private Node crossingTunnels(Node node, Node ignoreNode,
			Link link/*, Canvas canvas*/) {

		for (Link dummy: node.getLinksMap().values()) {
			if ((dummy.evenNode == node && dummy.oddNode != ignoreNode)) {
				if (colorCheck(dummy, link) == true) {
				//	simple.draw(canvas, dummy);
					return dummy.oddNode;
				}
			}

			if ((dummy.oddNode == node && dummy.evenNode != ignoreNode)) {
				if (colorCheck(dummy, link) == true) {
				//	simple.draw(canvas, dummy);
					return dummy.evenNode;
				}
			}
		}

		return null;
	}

	@Override
	public void draw(Canvas canvas, Link link) {
		if (link.smooth) {
			Node nodeTo = link.oddNode;
			Node nodeFrom = link.evenNode;

			Node nodeFromCorrector = crossingTunnels(nodeFrom, nodeTo,
					link);
			Node nodeToCorrector = crossingTunnels(nodeTo, nodeFrom,
					link);

			//simple.draw(canvas, oldLink);

			if (nodeFromCorrector == null || nodeToCorrector == null) {
				simple.draw(canvas, link);
				return;
			}

			float x0 = nodeTo.getPointF().x;
			float x1 = nodeToCorrector.getPointF().x;

			float y0 = nodeTo.getPointF().y;
			float y1 = nodeToCorrector.getPointF().y;

			float a1 = y1 - y0;
			float b1 = x0 - x1;
			float c1 = y0 * x1 - x0 * y1;

			x0 = nodeFrom.getPointF().x;
			x1 = nodeFromCorrector.getPointF().x;

			y0 = nodeFrom.getPointF().y;
			y1 = nodeFromCorrector.getPointF().y;

			float a2 = y1 - y0;
			float b2 = x0 - x1;
			float c2 = y0 * x1 - x0 * y1;

			float x = (b1 * c2 - b2 * c1) / (a1 * b2 - a2 * b1);
			float y = (c1 * a2 - c2 * a1) / (a1 * b2 - a2 * b1);

			PointF iPoint = new PointF(x, y);

			// CornerSmoother
			simple.draw(canvas, link.evenPointF, iPoint, link.colors);
			simple.draw(canvas, iPoint, link.oddPointF, link.colors);

			
			
		} else {
			simple.draw(canvas, link);
		}
	}

}
